package com.sale.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.core.utils.StringUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.system.api.RemoteUnitService;
import com.sale.system.api.domain.dto.MaterialAuxiliaryDto;
import com.sale.system.api.model.MaterialUnitDto;
import com.sale.system.domain.MaterialAccessories;
import com.sale.system.domain.MaterialAuxiliary;
import com.sale.system.domain.SysAuxiliaryUnitDetail;
import com.sale.system.domain.SysTheAlarm;
import com.sale.system.domain.dto.MaterialAccessoriesDto;
import com.sale.system.domain.dto.SysCategoryDto;
import com.sale.system.domain.vo.MaterialAccessoriesVo;
import com.sale.system.domain.vo.MaterialAlarmVo;
import com.sale.system.domain.vo.MaterialMqMessageVo;
import com.sale.system.mapper.*;
import com.sale.system.service.IMaterialAccessoriesService;
import com.sale.system.service.ISysCategoryService;
import com.sale.system.service.ISysDocumentService;
import com.sale.system.service.ISysMidSplitService;
import com.sale.system.util.MaterialMqUtil;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description 辅料信息实现层
 * @Date 23-12-06
 * @Author hl
 **/
@RequiredArgsConstructor
@Service
public class MaterialAccessoriesServiceImpl implements IMaterialAccessoriesService {

    private final MaterialAccessoriesMapper materialAccessoriesMapper;

    private final SysAuxiliaryUnitMapper sysAuxiliaryUnitMapper;

    private final MaterialAuxiliaryMapper materialAuxiliaryMapper;

    private final ISysDocumentService sysDocumentService;

    private final SysAuxiliaryUnitDetailMapper sysAuxiliaryUnitDetailMapper;

    private final SysTheAlarmMapper sysTheAlarmMapper;

    private final MaterialRawServiceImpl materialRawServiceImpl;

    private final ISysCategoryService sysCategoryService;

    private final ISysMidSplitService sysMidSplitService;

    /**
     * 获取辅料配置
     */
    @Override
    public TableDataInfo<MaterialAccessoriesDto> selectAccessoriesList(MaterialAccessoriesVo materialAccessoriesVo, PageQuery pageQuery) {
        Page<MaterialAccessoriesDto> page = materialAccessoriesMapper.selectAccessoriesList(pageQuery.build(), this.buildQueryWrapper(materialAccessoriesVo));
        List<MaterialAccessoriesDto> list = page.getRecords();
        //渲染辅助属性
//        // 多单位
//        List<SysTheDropDto> listThe = sysAuxiliaryUnitMapper.selectMultiMeteringUnitAllList();
//        Map<String, String> map = listThe.stream()
//            .collect(Collectors.toMap(SysTheDropDto::getValue, SysTheDropDto::getLabel));
        //单位集合
        for (MaterialAccessoriesDto dto :
            list) {
            dto.setAuxiliaryAttribute(materialAuxiliaryMapper.selectAuxiliaryById(dto.getMaterialId()));
        }
        return TableDataInfo.build(page);
    }

    private Wrapper<MaterialAccessoriesVo> buildQueryWrapper(MaterialAccessoriesVo materialAccessoriesVo) {
        QueryWrapper<MaterialAccessoriesVo> wrapper = Wrappers.query();
        wrapper
            .like(ObjectUtil.isNotNull(materialAccessoriesVo.getMaterialCode()), "t1.material_code", materialAccessoriesVo.getMaterialCode())
            .like(StringUtils.isNotBlank(materialAccessoriesVo.getMaterialName()), "t1.material_name", materialAccessoriesVo.getMaterialName())
            .eq(StringUtils.isNotBlank(materialAccessoriesVo.getMaterialStatus()), "t1.material_status", materialAccessoriesVo.getMaterialStatus())
            .eq(StringUtils.isNotBlank(materialAccessoriesVo.getMaterialType()), "t1.material_type", materialAccessoriesVo.getMaterialType()).between(materialAccessoriesVo.getCreateTime() != null && materialAccessoriesVo.getEndTime() != null,
                "t1.create_time", materialAccessoriesVo.getCreateTime(), materialAccessoriesVo.getEndTime());
        return wrapper;
    }

    /**
     * 新增辅料信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAccessories(MaterialAccessoriesVo materialAccessoriesVo) throws Exception {
        MaterialAccessories accessories = new MaterialAccessories();
        BeanUtils.copyProperties(materialAccessoriesVo, accessories);
        accessories.setMaterialId(IdWorker.getId());
        List<SysAuxiliaryUnitDetail> list2 = materialAccessoriesVo.getList();
        StringBuffer moreUnit = new StringBuffer();
        for (SysAuxiliaryUnitDetail item : list2) {
            moreUnit.append(item.getAuxiliaryId()).append(",");
            item.setMaterialId(accessories.getMaterialId());
        }
        //辅料编码按照类别配置中得生成
        SysCategoryDto sysCategoryDto = sysCategoryService.selectCategoryById(Long.parseLong(materialAccessoriesVo.getMaterialType()));
        String s = sysMidSplitService.selectSplitStr(sysCategoryDto.getCodeRule());
        if (StringUtils.isEmpty(s)) {
            throw new GlobalException("编码生成失败，请检查配置");
        }
        accessories.setMaterialCode(s);
        accessories.setCreateBy(LoginHelper.getUsername());
        accessories.setMaterialMoreUnit(moreUnit.toString().substring(0, moreUnit.length() - 1));
        int ins = materialAccessoriesMapper.insert(accessories);
        if (ins > 0) {
            if (materialAccessoriesVo.getAlarmCode() != null) {
                List<SysTheAlarm> list = materialRawServiceImpl.alarmConfiguration(materialAccessoriesVo.getAlarmCode());
                long op = accessories.getMaterialId();
                String materialCode = accessories.getMaterialCode();
                for (SysTheAlarm sysTheAlarm : list) {
                    String roles = "";
                    for (int i = 0; i < sysTheAlarm.getRoleIds().size(); i++) {
                        roles = roles + sysTheAlarm.getRoleIds().get(i);
                        if (sysTheAlarm.getRoleIds().size() - 1 != i) {
                            roles = roles + ",";
                        }
                    }
                    sysTheAlarm.setAlarmRoleId(roles);
                    sysTheAlarm.setAlarmAssociatedId(op);
                    sysTheAlarm.setAlarmOfMaterial(2);
                    sysTheAlarm.setAlarmMaterialCode(materialCode);
                }
                if (list.size() != 0) {
                    ins = sysTheAlarmMapper.insertSysTheAlarm(list);
                }
            }
            if (ins == 0) {
                throw new SQLException("抛出异常");
            }
        }
        //mq发送消息
        String userIdStr = LoginHelper.getUserIdStr();
        MaterialMqMessageVo materialMqVo = new MaterialMqMessageVo();
        BeanUtils.copyProperties(accessories, materialMqVo);
        materialMqVo.setUserIdStr(userIdStr);
        materialMqVo.setMaterialType(Long.parseLong(accessories.getMaterialType()));
        // materialMqVo.setMaxInventory(String.valueOf(accessories.getMaxInventory()));
        MaterialMqUtil.materialMqSend(materialMqVo);

        List<MaterialAuxiliary> list = materialAccessoriesVo.getAuxiliaryAttribute();
        if (list != null) {
            for (MaterialAuxiliary auxiliary : list) {
                auxiliary.setMaterialId(accessories.getMaterialId());
                auxiliary.setAuxiliaryId(IdWorker.getId());
            }
            materialAuxiliaryMapper.insertBatch(list);
        }
        if (list2.get(0).getAuxiliaryId() != null) {
            sysAuxiliaryUnitDetailMapper.insertBatch(list2);
        }
        return ins;
    }

    /**
     * 删除辅料信息
     */
    @Override
    public int deleteAccessories(String materialId) throws Exception {
        String[] materialIdS = materialId.split(",");
        ArrayList<String> arrayList = new ArrayList<>();
        for (String str :
            materialIdS) {
            arrayList.add(str);
            //删除对应属性
            HashMap<String, Object> map = new HashMap<>();
            map.put("material_id", str);
            materialAuxiliaryMapper.deleteByMap(map);
            sysAuxiliaryUnitDetailMapper.deleteByMap(map);
        }
        //mq发送消息(删除)
        MaterialMqMessageVo materialMqVo = new MaterialMqMessageVo();
        materialMqVo.setIdStr(materialId);
        MaterialMqUtil.materialMqSendDelete(materialMqVo);
        return materialAccessoriesMapper.deleteBatchIds(Arrays.asList(materialIdS));
    }

    /**
     * 根据编号获取详细信息
     */
    @Override
    public MaterialAccessoriesDto selectAccessoriesById(long materialId) {
        MaterialAccessoriesDto dto = new MaterialAccessoriesDto();
        MaterialAccessories accessories = materialAccessoriesMapper.selectById(materialId);
        BeanUtils.copyProperties(accessories, dto);
        dto.setMaterialUnit(String.valueOf(accessories.getMaterialUnit()));
        List<MaterialAuxiliaryDto> list = materialAuxiliaryMapper.selectAuxiliaryById(materialId);
        dto.setAuxiliaryAttribute(list);
        Map<String, Object> map = new HashMap<>();
        map.put("material_id", materialId);
        List<SysAuxiliaryUnitDetail> list1 = sysAuxiliaryUnitDetailMapper.selectByMap(map);
        //获取告警信息数据
        int alarmOfMaterial = 2;
        List<SysTheAlarm> theList = sysTheAlarmMapper.selectSysTheAlarmList(materialId,alarmOfMaterial);
        MaterialAlarmVo materialAlarmVo = materialRawServiceImpl.alarmConfigtType(theList);
        dto.setAlarmCode(materialAlarmVo);
        dto.setList(list1);
        return dto;
    }

    /**
     * 修改辅料信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateAccessoriesEdit(MaterialAccessoriesVo materialAccessoriesVo) throws Exception {
        MaterialAccessories accessories = new MaterialAccessories();
        BeanUtils.copyProperties(materialAccessoriesVo, accessories);
        List<SysAuxiliaryUnitDetail> list2 = materialAccessoriesVo.getList();
        StringBuffer moreUnit = new StringBuffer();
        for (SysAuxiliaryUnitDetail item : list2) {
            moreUnit.append(item.getAuxiliaryId()).append(",");
            item.setMaterialId(accessories.getMaterialId());
        }
        if (list2.size()>0){
            accessories.setMaterialMoreUnit(moreUnit.toString().substring(0, moreUnit.length() - 1));
        }
        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("material_id", materialAccessoriesVo.getMaterialId());
        sysAuxiliaryUnitDetailMapper.deleteByMap(map2);
        sysAuxiliaryUnitDetailMapper.deleteByMap(map2);
        sysAuxiliaryUnitDetailMapper.insertBatch(list2);
        int ors = materialAccessoriesMapper.updateById(accessories);
        long sy =  materialAccessoriesVo.getMaterialId();
        String materialCode = materialAccessoriesVo.getMaterialCode();
        sysTheAlarmMapper.deleteSysTheAlarmOnById(sy);
        if(ors>0){
            List<SysTheAlarm> list = materialRawServiceImpl.alarmConfiguration(materialAccessoriesVo.getAlarmCode());
            for (SysTheAlarm sysTheAlarm:
                list) {

                String roles = "";
                for (int i = 0; i < sysTheAlarm.getRoleIds().size(); i++) {
                    roles = roles + sysTheAlarm.getRoleIds().get(i);
                    if (sysTheAlarm.getRoleIds().size()-1!=i){
                        roles = roles + ",";
                    }

                }
                sysTheAlarm.setAlarmRoleId(roles);
                sysTheAlarm.setAlarmAssociatedId(sy);
                sysTheAlarm.setAlarmOfMaterial(2);
                sysTheAlarm.setAlarmMaterialCode(materialCode);
            }
            if (list.size()!=0){
                ors = sysTheAlarmMapper.insertSysTheAlarm(list);
            }
            if(ors == 0){
                throw new SQLException("抛出异常");
            }
        }else{
            throw new SQLException("抛出异常");
        }
        //mq发送消息
        String userIdStr = LoginHelper.getUserIdStr();
        MaterialMqMessageVo materialMqVo = new MaterialMqMessageVo();
        BeanUtils.copyProperties(accessories, materialMqVo);
        materialMqVo.setUserIdStr(userIdStr);
        materialMqVo.setMaterialType(Long.parseLong(accessories.getMaterialType()));
        //materialMqVo.setMaxInventory(String.valueOf(accessories.getMaxInventory()));
        MaterialMqUtil.materialMqSend(materialMqVo);
        List<MaterialAuxiliary> list = materialAccessoriesVo.getAuxiliaryAttribute();
        if (list != null) {
            //删除对应属性
            HashMap<String, Object> map = new HashMap<>();
            long materialId = accessories.getMaterialId();
            map.put("material_id", materialId);
            materialAuxiliaryMapper.deleteByMap(map);
            //重新新增对应属性
            for (MaterialAuxiliary auxiliary : list) {
                auxiliary.setMaterialId(materialId);
            }
            //批量新增物料属性信息
            materialAuxiliaryMapper.insertBatch(list);
        }
        return ors;
    }

    @Override
    public int updateAccessoriesEditFreeze(MaterialAccessoriesVo materialAccessoriesVo) {
        return 0;
    }

    /**
     * 辅料冻结
     */
    @Override
    public int updateEditFreeze(Long materialId) {
        MaterialAccessories accessories = new MaterialAccessories();
        accessories.setMaterialId(materialId);
        accessories.setMaterialStatus(1);
        return materialAccessoriesMapper.updateById(accessories);
    }

    /**
     * 辅料解结
     */
    @Override
    public int updateEditThaw(Long materialId) {
        MaterialAccessories accessories = new MaterialAccessories();
        accessories.setMaterialId(materialId);
        accessories.setMaterialStatus(2);
        return materialAccessoriesMapper.updateById(accessories);
    }


}
